# -*- coding: utf-8 -*-
"""
@project: SYL-Index-Sys

@desc: 用户管理部分
包括：1.展示用户的列表
    2.查看用户详细信息
    3.编辑用户权限
    4.添加用户
    5.删除用户
Note: 这部分权限是学校管理员拥有.
"""
from flask_login import login_required, current_user
from flask import jsonify
from flask import Blueprint, request
from models import User, Subject, Point
import json
from app import db
import hashlib

user_manage = Blueprint('user_manage', __name__)

@user_manage.route('/user-manage/show-users')
@login_required
def show_users():
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    data = []
    for i, u in enumerate(User.query.filter_by(is_active='Y').all()):
        temp = {}
        temp['num'] = i
        temp['user_id'] = u.id
        temp['department'] = u.department
        temp['name'] = u.name
        temp['role_type'] = u.role.name if u.role else ''
        temp['controls'] = []
        if u.role_id == 2:
            points = Point.query.filter_by(user_id = u.id).all()
            for p in points:
                c = {}
                c['id'] = p.id
                c['point'] = p.point
                temp['controls'].append(c)
        if u.role_id == 3:
            subjects = Subject.query.filter_by(user_id=u.id).all()
            for s in subjects:
                c = {}
                c['id'] = s.id
                c['code'] = s.code
                c['name'] = s.name
                temp['controls'].append(c)
        temp['role_id'] = u.role_id
        data.append(temp)
    return json.dumps({'data':data}, ensure_ascii=False)

@user_manage.route('/user-manage/show-details/<user_id>')
@login_required
def show_user_details(user_id):
    res = {}
    u = User.query.filter_by(id=user_id).first()
    res['controls'] = []
    if u.role_id == 2:
        points = Point.query.filter_by(user_id=user_id).all()
        for p in points:
            temp = {}
            temp['id'] = p.id
            temp['project'] = p.project
            temp['factor'] = p.factor
            temp['point'] = p.point
            res['controls'].append(temp)
    if u.role_id == 3:
        subjects = Subject.query.filter_by(user_id = user_id).all()
        for s in subjects:
            temp = {}
            temp['id'] = s.id
            temp['code'] = s.code
            temp['name'] = s.name
            res['controls'].append(temp)
    res['username'] = u.username
    res['department'] = u.department
    res['telephone_num'] = u.telephone_num
    res['mobile_phone_num'] = u.mobile_phone_num
    res['email'] = u.email
    res['office_telephone'] = u.office_telephone
    res['role_type'] = u.role.name
    res['role_id'] = u.role_id
    return json.dumps({'data':res}, ensure_ascii=False)

@user_manage.route('/user-manage/del-user-points', methods=['POST'])
@login_required
def del_user_points():
    """
    删除用户绑定的监测点
    :return:
    """
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code":403, "info":"您没有权限删除用户绑定的监测点"}, ensure_ascii=False)
    request_data = json.loads(request.get_data().decode('utf-8'))
    points = request_data.get('points') # 之前绑定的point
    try:
        for p in points:
            Point.query.filter_by(id=p).update({"user_id": None})
            db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        return json.dumps({"status_code":400, "info":"删除用户绑定监测点失败"})
    return json.dumps({"status_code": 200, "info": "删除用户绑定监测点成功"})

@user_manage.route('/user-manage/del-user-subjects', methods=['POST'])
@login_required
def del_user_subjects():
    """
    删除用户绑定学科
    :return:
    """
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code": 403, "info": "您没有权限删除用户绑定的学科"}, ensure_ascii=False)
    request_data = json.loads(request.get_data().decode('utf-8'))
    user_id = request_data.get('user_id')
    subject_id = request_data.get('subject_id') #用户发来的学科
    try:
        Subject.query.filter_by(id=subject_id).update({"user_id":None})
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        return json.dumps({"status_code":400, "info":"删除用户绑定学科失败"})
    return json.dumps({"status_code":200, "info":"删除用户绑定学科成功"})


@user_manage.route('/user-manage/assign-user-subjects', methods=['POST'])
@login_required
def assign_user_subjects():
    # 分配用户学科
    request_data = json.loads(request.get_data().decode('utf-8'))
    user_id = request_data.get('user_id')
    subject_id = request_data.get('subject_id') #用户发来的学科id
    try:
        Subject.query.filter_by(id=subject_id).update({"user_id": user_id})
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback() # 回滚
        return json.dumps({"status_code":400, "info":"用户学科权限分配失败"})
    return json.dumps({"status_code": 200, "info": "用户学科权限分配完成"})


@user_manage.route('/user-manage/assign-user-points', methods=['POST'])
@login_required
def assign_user_points():
    # 给用户分配大学检测点
    request_data = json.loads(request.get_data().decode('utf-8'))
    user_id = request_data.get('user_id')
    points = request_data.get('points')
    try:
        for p in points:
            Point.query.filter_by(id=p).update({"user_id":user_id})
            db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        return json.dumps({"status_code": 400, "info": "用户大学指标权限分配失败"})
    return json.dumps({"status_code":200, "info":"用户大学指标权限分配完成"})


@user_manage.route('/user-manage/allow-subjects')
@login_required
def allow_subjects():
    """
    加载所有可以使用的学科
    :param user_id:
    :return:
    """
    subjects = Subject.query.filter_by(user_id=None).all()
    data = []
    for subject in subjects:
        data_json = {}
        data_json['id'] = subject.id
        data_json['code'] = subject.code
        data_json['name'] = subject.name
        data.append(data_json)
    return json.dumps({"data":data}, ensure_ascii=False)

@user_manage.route('/user-manage/allow-university-points')
@login_required
def allow_university_points():
    """
    加载所有可以使用的大学指标检测点
    :param user_id:
    :return:
    """
    points = Point.query.filter_by(point_type='D', user_id=None).all()
    data = []
    for point in points:
        data_json = {}
        data_json['id'] = point.id
        data_json['point'] = point.point
        data_json['factor'] = point.factor # 检测要素
        data.append(data_json)
    return json.dumps({"data":data}, ensure_ascii=False)

@user_manage.route('/user-manage/assign-to-manager', methods=['POST'])
@login_required
def assign2manager():
    """
    将用户分配为管理员
    :return:
    """
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    request_data = json.loads(request.get_data().decode('utf-8'))
    user_id = request_data.get('user_id')
    User.query.filter_by(id=user_id).update({"role_id":1})
    db.session.commit()

@user_manage.route('/user-manage/delete/<user_id>')
@login_required
def delete_user(user_id):
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    try:
        user= User.query.get(user_id)
        User.query.filter_by(id=user_id).update({"is_active":"N"})
        if user.role_id == 3:
            Subject.query.filter_by(user_id=user_id).update({"user_id": None})
        if user.role_id == 2:
            Point.query.filter_by(user_id=user_id).update({"user_id": None})
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        return json.dumps({"status_code":400, "info":"删除失败"}, ensure_ascii=False)
    return json.dumps({"status_code":200, "info":"成功删除该用户"}, ensure_ascii=False)

@user_manage.route('/user-manage/add-user', methods=['POST'])
@login_required
def add_user():
    """
    添加用户.
    :return:
    """
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    request_data = json.loads(request.get_data().decode('utf-8'))
    username = request_data['username']
    password = request_data['password']
    role_id = request_data['role_id']
    user = User(username=username, password=password, role_id=role_id, is_active='Y')
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        return json.dumps({"status_code": 400, "info": "添加用户失败"}, ensure_ascii=False)
    return json.dumps({"status_code":200, "info": "添加成功"}, ensure_ascii=False)


@user_manage.route('/user-manage/recover-user', methods=['POST'])
@login_required
def recover_user():
    """
    恢复用户，密码恢复为默认。
    :return:
    """
    role_id = current_user.role_id
    if role_id != 1: # 只有管理员才能恢复
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    request_data = json.loads(request.get_data().decode('utf-8'))
    username = request_data.get('username')
    User.query.filter_by(username = username).update({"password":'123456'})
    db.session.commit()
    return json.dumps({"status_code":200, "info": "用户恢复成功"})

@user_manage.route('/user-manage/all-subjects')
@login_required
def all_subjects():
    """
    展示所有的学科，不加任何限制
    :return:
    """
    subjects = Subject.query.all()
    data = []
    for subject in subjects:
        data_json = {}
        data_json['id'] = subject.id
        data_json['code'] = subject.code
        data_json['name'] = subject.name
        data.append(data_json)
    return json.dumps({"data":data}, ensure_ascii=False)

@user_manage.route('/user-manage/change-user-information', methods=['POST'])
@login_required
def change_user_info():
    """
    修改个人信息
    :return:
    """
    request_data = json.loads(request.get_data().decode('utf-8'))
    q = User.query.filter_by(id=request_data['id'])
    user = User.query.filter_by(id=request_data['id']).first()
    name = request_data['name']
    oldPassword = request_data['oldPassword']
    newPassword = request_data['newPassword']
    officePhone = request_data['officePhone']
    email = request_data['email']
    if oldPassword != user.password:
        return json.dumps({"status_code": 401, "reason": "原始密码验证错误"})
    try:
        q.update({"password":newPassword,
                  "office_telephone":officePhone,
                  "name": name,
                  "email":email})
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        return json.dumps({"status_code": 401, "info": "用户信息更新失败"}, ensure_ascii=False)
    return json.dumps({"status_code":200, "info":"更改用户信息成功"}, ensure_ascii=False)



